package com.android.love.ui;

import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Dialog;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnKeyListener;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;

import com.android.love.MyApplication;
import com.android.love.R;

public class BetterActivityHelper {

	// FIXME: this method currently doesn't work as advertised
	public static int getWindowFeatures(Activity activity) {
		Window window = activity.getWindow();
		if (window == null) {
			return 0;
		}
		try {
			// Method m =
			// activity.getWindow().getClass().getMethod("getFeatures");
			// Method[] m = window.getClass().getMethods();
			// m.setAccessible(true);
			// return (Integer) m.invoke(window);
			return 0;
		} catch (Exception e) {
			return 0;
		}
	}

	/**
	 * 创建一个ProgressDialog
	 * 
	 * @param activity
	 * @param progressDialogTitleId
	 *            标题资源id .如果小于或者等于0，使用默认id
	 * @param progressDialogMsgId
	 *            信息id
	 * @return The new dialog
	 */
	public static ProgressDialog createProgressDialog(final Activity activity,
			int progressDialogTitleId, int progressDialogMsgId) {
		ProgressDialog progressDialog = new ProgressDialog(activity);
		if (progressDialogTitleId <= 0) {
			progressDialogTitleId = R.string.app_name;
		}
		progressDialog.setTitle(progressDialogTitleId);
		if (progressDialogMsgId <= 0) {
			progressDialogMsgId = R.string.process_tip;
		}
		progressDialog.setMessage(activity.getString(progressDialogMsgId));
		progressDialog.setIndeterminate(true);
		progressDialog.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				activity.onKeyDown(keyCode, event);
				return false;
			}
		});
		// progressDialog.setInverseBackgroundForced(true);
		return progressDialog;
	}

	/**
	 * Creates a new Yes/No AlertDialog
	 * 
	 * @param context
	 * @param dialogTitle
	 * @param screenMessage
	 * @param iconResourceId
	 * @param listener
	 * @return
	 */
	public static AlertDialog newYesNoDialog(final Context context,
			String dialogTitle, String screenMessage, int iconResourceId,
			OnClickListener listener) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setCancelable(false);
		builder.setPositiveButton(android.R.string.yes, listener);
		builder.setNegativeButton(android.R.string.no, listener);

		builder.setTitle(dialogTitle);
		builder.setMessage(screenMessage);
		builder.setIcon(iconResourceId);

		return builder.create();
	}

	/**
	 * 创建一个新AlertDialog，展示一些简单信息
	 * 
	 * @param context
	 * @param dialogTitle
	 * @param screenMessage
	 * @param iconResourceId
	 * @return
	 */
	public static AlertDialog newMessageDialog(final Context context,
			String dialogTitle, String screenMessage, int iconResourceId) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setCancelable(false);
		builder.setPositiveButton("确定", new OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});

		builder.setTitle(dialogTitle);
		builder.setMessage(screenMessage);
		builder.setIcon(iconResourceId);

		return builder.create();
	}

	/**
	 * 创建一个自定义dialog
	 * 
	 * @param context
	 * @param theme  
	 * @param view
	 * @return
	 */
	public static Dialog newCustomDialog(final Context context, int theme,
			View view) {
		Dialog customDialog = new Dialog(context, theme);
		customDialog.setCancelable(false);
		customDialog.setContentView(view);
		return customDialog;
	}

	/**
	 * 检查应用是否在后台
	 * 
	 * @param context
	 * @return true 当另一个应用在当前应用的上面
	 */
	public static boolean isApplicationBroughtToBackground(final Context context) {
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasks = am.getRunningTasks(1);
		if (!tasks.isEmpty()) {
			ComponentName topActivity = tasks.get(0).topActivity;
			if (!topActivity.getPackageName().equals(context.getPackageName())) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Determines whether an application is about to close, in which case it
	 * will invoke the {@link MyApplication#onClose()} life-cycle handler.
	 * Application close is being defined as the transition of the last running
	 * Activity of the current application to the Android home screen using the
	 * BACK button.
	 * 
	 * @param context
	 *            the current context
	 * @param keyCode
	 *            the key code of the key event (if not
	 *            {@link KeyEvent#KEYCODE_BACK}, this method is a no-op)
	 */
	static void handleApplicationClosing(final Context context, int keyCode) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			ActivityManager am = (ActivityManager) context
					.getSystemService(Context.ACTIVITY_SERVICE);
			List<RunningTaskInfo> tasks = am.getRunningTasks(2);

			RunningTaskInfo currentTask = tasks.get(0);
			RunningTaskInfo nextTask = tasks.get(1);

			// if we're looking at this application's base/launcher Activity,
			// and the next task is the Android home screen, then we know we're
			// about to close the app
			if (currentTask.topActivity.equals(currentTask.baseActivity)
					&& nextTask.baseActivity.getPackageName().startsWith(
							"com.android.launcher")) {
				MyApplication application = (MyApplication) context
						.getApplicationContext();
				application.onClose();
			}
		}
	}
}
